package com.gensdai.leliang.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.dialog.Select_Share;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.entity.Call;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.remoteInterface.URLConfig;

import com.gensdai.leliang.view.Toaster;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/6/2.
 */

public class Invite_friend extends BaseActivityNoAbs implements View.OnClickListener {

    @BindView(R.id.ui_title)
    TextView uiTitle;
    @BindView(R.id.invite_number)
    TextView invite_number;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.immediately)
    ImageView immediately; //立即邀请
    @BindView(R.id.qr_invite_img)
    ImageView qr_invite_img; //二维码立即邀请
    @BindView(R.id.invite_img)
    ImageView invite_img; //邀请记录
    Tencent mTencent;

    private boolean qr = false;
    Select_Share share;
    SharedPreferences mshare;
    private final String WX_APP_ID = "wx701d441207f210af";
    private String path;
    private boolean QR = false;
    private Upload up;
    private String img_path;
    private final int ENTER = 1;//
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ENTER:
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            img_path = new JSONObject(
                                    (String) msg.obj).
                                    getJSONObject("data").
                                    getString("QRcode");
                            //下载图片
                            GetImageInputStream(img_path);
                            //缓存图片到本地
//                            SavaImage(, path);
                            qr = true;
                        } else {
                            Toast.makeText(
                                    Invite_friend.this,
                                    new JSONObject((String) msg.obj)
                                            .getString("message"),
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    up.dismiss();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTencent = Tencent.createInstance("1106232764", this.getApplicationContext());
        setContentView(R.layout.invite_friend);
        ButterKnife.bind(this);
        init();
        getQR();
    }

    /**
     * 初始化
     */
    private void init() {

        uiTitle.setText(getString(R.string.invite_friend));
        invite_number.setText(getSharedPreferences("User", MODE_PRIVATE).getString("userno", ""));
        share = new Select_Share(this);
        up = new Upload(this);
        mshare = getSharedPreferences("User", MODE_PRIVATE);

//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            //SD卡已装入
//            path = Environment.getExternalStorageDirectory().getPath() + "/lelongQR";
//        } else {
        path = this.getExternalFilesDir(null).getPath() + "/lelongQR";
//        }

        Log.e("path", path);
        back.setOnClickListener(this);
        immediately.setOnClickListener(this);
        invite_img.setOnClickListener(this);
        qr_invite_img.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                this.finish();
                break;
            case R.id.immediately:
                QR = false;
                share.show();
                break;
            case R.id.qr_invite_img:
                if (!qr) {
                    Toaster.showDefToast(this, "二维码正在生成中，请稍等!~");
                    return;
                }
                QR = true;
                share.show();

//                Intent intent = new Intent(Intent.ACTION_SEND);
//                intent.setType("image/jpeg");//图片
////                File image = new File(path + "/" + mshare.getString("userno", "-1") + ".jpg");
//                File image = new File(path + "/" + "一码不扫，何以扫天下！~" + ".jpg");
//                Uri uri = Uri.fromFile(image);//图片路径
//                //发送图片给好友。
//                intent.putExtra(Intent.EXTRA_STREAM, uri);
//                intent.setComponent(comp);
//                intent.setAction(Intent.ACTION_SEND);
//                intent.putExtra(Intent.EXTRA_SUBJECT, "乐粮乐成长");
////                intent.putExtra(Intent.EXTRA_TEXT, "一码不扫，何以扫天下！~");
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(Intent.createChooser(intent, "分享二维码"));
                break;
            case R.id.invite_img:
                Intent intent = new Intent(this, invite_friend_deal.class);
                intent.putExtra("flag","1");
                startActivity(intent);
                break;
            case R.id.qq:
                onClickShare();
                break;
            case R.id.wx:
                onClickShareWX(0);
                break;
            case R.id.wxpyq:
                onClickShareWX(1);
                break;
            case R.id.cancel:
                share.dismiss();
                break;
            default:
                break;
        }
    }

    /**
     * 分享到QQ
     */
    private void onClickShare() {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
                QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "乐粮乐成长");
        if (QR) {
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "一码不扫，何以扫天下！~");
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, img_path);
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, img_path);
        } else {
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "不仅仅是给宝宝带来好东西的分享购物平台！");
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,
                    URLConfig.BASEDOMAIN
                            + "lelongWx/wxUser/invite.html?userNo=" + getSharedPreferences("User", MODE_PRIVATE).getString("userno", ""));
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "https://www.gensdai.com"
                    + "/common/views/images/applogo.png");
        }
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "乐粮乐成长");
        // params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, "其他附加功能");
        mTencent.shareToQQ(this, params, new BaseUiListener());
    }

    /**
     * 分享到微信
     */
    private void onClickShareWX(int flag) {
        IWXAPI wxApi = WXAPIFactory.createWXAPI(this, WX_APP_ID);
        wxApi.registerApp(WX_APP_ID);

        WXWebpageObject webpage = new WXWebpageObject();
        WXMediaMessage msg;
        if (QR) {
            webpage.webpageUrl = img_path;
            msg = new WXMediaMessage(webpage);
            msg.title = "乐粮乐成长";
            msg.description = "一码不扫，何以扫天下！~";
            //这里替换一张自己下载的图片资源
            msg.setThumbImage(bitmap);
        } else {
            webpage.webpageUrl = URLConfig.BASEDOMAIN
                    + "lelongWx/wxUser/invite.html?userNo=" + getSharedPreferences("User", MODE_PRIVATE).getString("userno", "");
            msg = new WXMediaMessage(webpage);
            msg.title = "乐粮乐成长";
            msg.description = "不仅仅是给宝宝带来好东西的分享购物平台！";
            //这里替换一张自己工程里的图片资源
            Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.app_logo);
            msg.setThumbImage(thumb);
        }

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        wxApi.sendReq(req);
    }

    /**
     * 生成二维码
     */
//    private void creatQR() {
//        Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.app_logo);
//        String path = Environment.getExternalStorageDirectory().toString() + "/lelongQR/" + System.currentTimeMillis() + ".jpg";
//        QRCodeUtil.createQRImage(URLConfig.BASEDOMAIN
//                + "lelongWx/wxUser/invite.html?userNo=" + getSharedPreferences("User", MODE_PRIVATE).getString("recommendUserNo", ""), 50, 50, logo, path);
//    }


    /**
     * 获得二维码
     */
    private void getQR() {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userNo", mshare.getString("userno", "")); //订单id
        DeleteToStr(loginParams);
    }

    //返回字符串类型
    private void DeleteToStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).INVITE_FRIEND_CODE(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = ENTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    Bitmap bitmap = null;

    /**
     * 获取网络图片
     *
     * @param imageurl 图片网络地址
     * @return Bitmap 返回位图
     */
    public void GetImageInputStream(final String imageurl) {
        Log.e("imageurl", imageurl);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL u = new URL(imageurl);
                    HttpURLConnection c = (HttpURLConnection) u.openConnection();
                    c.setRequestMethod("GET");
                    c.setDoOutput(true);
                    c.connect();
                    InputStream in = c.getInputStream();
                    bitmap = BitmapFactory.decodeStream(in);
//                    immediately.setImageBitmap(bitmap);
                    if (bitmap != null) {
                        SavaImage(bitmap, path);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }


    /**
     * 保存位图到本地
     *
     * @param bitmap
     * @param path   本地路径
     * @return void
     */
    public void SavaImage(Bitmap bitmap, String path) {
//        File file = new File(path, mshare.getString("userno", "-1") + ".jpg");
        File file = new File(path, "一码不扫，何以扫天下！~" + ".jpg");
        Log.e("file", file.getPath());
        FileOutputStream fileOutputStream = null;
        try {
            //文件夹不存在，则创建它
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();

            }
            if (!file.exists()) {
                file.createNewFile();
                fileOutputStream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 2, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
            } else {
//                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onCancel() {
            // TODO Auto-generated method stub

        }

        @Override
        public void onComplete(Object arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onError(UiError arg0) {
            // TODO Auto-generated method stub
        }
    }


}
